package com.dengxiujun.simpletomcat.dispatcher;

import com.dengxiujun.simpletomcat.config.ServletMappingConfig;
import com.dengxiujun.simpletomcat.request.HttpRequest;
import com.dengxiujun.simpletomcat.response.HttpResponse;
import com.dengxiujun.simpletomcat.servlet.HttpServlet;

import java.io.IOException;

/**
 * <p></p>
 *
 * @author dengxiujun
 * @date 2021-04-26
 **/
public class ServletDispatcher {

    public static void dispatch(HttpRequest req, HttpResponse rep) throws IOException {
        if (ServletMappingConfig.SERVLET_MAPPER.containsKey(req.getUrl())) {
            try {
                @SuppressWarnings("unchecked")
                Class<HttpServlet> servletClass = (Class<HttpServlet>) Class.forName(ServletMappingConfig.SERVLET_MAPPER.get(req.getUrl()));
                HttpServlet servletInstance = servletClass.newInstance();
                servletInstance.service(req, rep);
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                switch (e.getClass().getName()) {
                    case "java.lang.ClassNotFoundException":
                        rep.write("找不到对应的Servlet");
                        break;
                    case "java.lang.InstantiationException":
                        rep.write("Servlet实例化失败");
                        break;
                    case "java.lang.IllegalAccessException":
                        rep.write("Servlet实例化失败(无参构造方法权限不够)");
                        break;
                }
                e.printStackTrace();
            }
        } else {
            rep.write("404 Error!");
        }
    }

}
